package com.netty.bfport.http.common.es;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netty.bfport.http.domain.dto.HealthyHistoryDTO;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: zhaoyang05
 * @Data: 2022/3/28 13:52
 * @Description
 */
@Component
public class EsUtils {
//
//    @Resource
//    RestHighLevelClient restHighLevelClient;


    @Autowired
    RestHighLevelClient client;
    /**
     * 创建索引
     * @param
     * @throws IOException
     */
//    @GetMapping("/test")
    public void createIndex(String index) throws IOException {
        CreateIndexRequest request = new CreateIndexRequest(index);
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println("createIndex: " + JSON.toJSONString(createIndexResponse));
    }

//    public static void before() {
//        String INDEX_TEST = "index_test";
//        TYPE_TEST = "type_test";
//        testsList = new ArrayList<>();
//        for (int i = 0; i < 100; i++) {
//            UserMsgDO userMsgDO = new UserMsgDO();
//            userMsgDO.setId(Long.valueOf(i));
//            userMsgDO.setName("this is the test " + i);
//            testsList.add(tests);
//        }
//    }
    /**
     * 添加文章
     * */
    public void add(String index, String type, JSONObject obj) throws IOException {
        IndexRequest indexRequest = new IndexRequest(index, type, obj.getString("id"));
        indexRequest.source(JSON.toJSONString(obj), XContentType.JSON);
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println("add: " + JSON.toJSONString(indexResponse));
    }


    /**
     * 根据id获取单条数据
     * */
    public void get() throws IOException {
        GetRequest getRequest = new GetRequest("zy", "zy", "qwewqeqw");
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
//        System.out.println("get: " + JSON.toJSONString(getResponse));
    }

    /**
     * 自定义查询规则
     * */
    public List<HealthyHistoryDTO> searchHistoryHealthy(String userId, Long startTime, Long endTime,String... indexs) throws IOException {
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
        boolBuilder.must(QueryBuilders.matchQuery("userId", userId));
        boolBuilder.must(QueryBuilders.matchQuery("history", "1"));
        boolBuilder.must(QueryBuilders.rangeQuery("createTime").from(startTime).to(endTime));
        // boolBuilder.must(QueryBuilders.matchQuery("id", tests.getId().toString()));

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolBuilder);
        sourceBuilder.from(0);
        sourceBuilder.size(5000); // 获取记录数，默认10
        sourceBuilder.fetchSource(new String[] {}, new String[] {}); // 第一个是获取字段，第二个是过滤的字段，默认获取全部
        SearchRequest searchRequest = new SearchRequest(indexs);
        searchRequest.types("user");
        searchRequest.source(sourceBuilder);
//        System.out.println(searchRequest);
        searchRequest.indicesOptions(IndicesOptions.fromOptions(true,true,true,false));
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
//        System.out.println("search: " + JSON.toJSONString(response));
        SearchHits hits = response.getHits();
        SearchHit[] searchHits = hits.getHits();
        List<HealthyHistoryDTO> healthyHistoryDTOS = new ArrayList<>();
        Arrays.stream(searchHits).forEach(e->{
            healthyHistoryDTOS.add(JSON.parseObject(e.getSourceAsString(),HealthyHistoryDTO.class));
        });
        return healthyHistoryDTOS;
//        for (SearchHit hit : searchHits) {
//
//            System.out.println("search -> " + hit.getSourceAsString());
//        }
    }

    /**
     * 自定义查询规则
     * TODO: 以后新增的查询可以基于这个自定义修改
     * */
    public void searchmodel(String sex,String startTime,String endTime) throws IOException {
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
        boolBuilder.must(QueryBuilders.matchQuery("userId", sex));
        boolBuilder.must(QueryBuilders.rangeQuery("create_time").from(startTime).to(endTime));
        // boolBuilder.must(QueryBuilders.matchQuery("id", tests.getId().toString()));
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolBuilder);
        sourceBuilder.from(0);
        sourceBuilder.size(1000); // 获取记录数，默认10
        sourceBuilder.fetchSource(new String[] {}, new String[] {}); // 第一个是获取字段，第二个是过滤的字段，默认获取全部
        SearchRequest searchRequest = new SearchRequest("test");
        searchRequest.types("user");
        searchRequest.source(sourceBuilder);
        System.out.println(searchRequest);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println("search: " + JSON.toJSONString(response));
        SearchHits hits = response.getHits();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit hit : searchHits) {
            System.out.println("search -> " + hit.getSourceAsString());
        }
    }





}
